<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;

use App\Http\Model\Orders;
use App\Http\Model\User;
use App\Http\Model\OrdersInfo;
use DB;
use EasyWeChat\Payment\Order;
use EasyWeChat\Foundation\Application;
use Config;

class OrdersController extends Controller
{
    //
    public function ordersList(){
    	$orders = new Orders;
    	$ordersInfo = $orders->get();
    	$ordersInfoHight = $orders->select("orders.*", DB::raw('count(orders.id) as sum'))->leftJoin("orders_info", "orders.id", "=", "orders_id")->groupBy("orders_id")->orderBy("sum", "desc")->first();
    	return view("admin.orders.orders-list", ["ordersInfo"=>$ordersInfo, "ordersInfoHight"=>$ordersInfoHight]);
    }
    public function ordersDetail($id){
    	$orders = new Orders;
    	$ordersInfo = $orders->find($id);
    	return view("admin.orders.orders-detail", ["ordersInfo"=>$ordersInfo]);
    }
    public function sendList(){
        $orders = new Orders;
        $ordersInfo = $orders->select("orders.*","orders_info.refund_status")->leftJoin("orders_info", "orders.id", "=", "orders_id")->where("status", 2)->where("refund_status", 0)->get();
        return view("admin.orders.send-list", ["ordersInfo"=>$ordersInfo]);
    }
    public function send(Request $request){
        $id = $request->input("id");
        $logistic_code = $request->input("logistic_code");
        $user = new User;
        $orders = new Orders;
        $ordersInfo = $orders->find($id);
        $userInfo = $user->find($ordersInfo->user_id);
        $ordersInfo->status = 3;
        $ordersInfo->send_at = date("Y-m-d H:i:s");
        $ordersInfo->logistic_code = $logistic_code;
        $this->goods_template($userInfo,$logistic_code,$id);
        $ordersInfo->save();
        echo 1;die;
    }
    public function refundList(){
        $ordersInfo = new OrdersInfo;
        $ordersInfoData = $ordersInfo->where("refund_status", 1)->get();
        return view("admin.orders.refund-list", ["ordersInfo"=>$ordersInfoData]);
    }
    public function refund(Request $request){
        $id = $request->input("id");
        $app = new Application(config('wechat'));
        $payment = $app->payment;
        $ordersInfo = new OrdersInfo;
        $ordersInfoData = $ordersInfo->find($id);
        $orderNo = $ordersInfoData->orders->transaction_id;
        $refundNo = $ordersInfoData->orders->num;
        $res = $payment->refundByTransactionId($orderNo, $refundNo, $ordersInfoData->price);
        if($res->return_code == "SUCCESS" && $res->result_code == "SUCCESS"){
            if($res->return_msg == "OK"){
                $ordersInfoData->refund_status = 3;
                $ordersInfoData->save();
                echo 1;die;
            }
        }
        echo 0;die;
    }
    public function refundFail(Request $request){
        $id = $request->input("id");
        $info = $request->input("info");
        $ordersInfo = new OrdersInfo;
        $ordersInfoData = $ordersInfo->find($id);
        // dd($ordersInfoData);
        $ordersInfoData->refund_status = 2;
        $ordersInfoData->refund_fail_message = $info;
        $ordersInfoData->save();
        echo 1;die;
    }

    // 快递查询
    public function logistic($id){
        $orders = new Orders;
        $ordersInfo = $orders->find($id);
        $num = $ordersInfo->num;
        // $num = '51010904478878935';
        $logistic_code = $ordersInfo->logistic_code;
        // $logistic_code = '3976331681071';
        $logistic_company = Config::get('app.kdn_company_name');
        // $logistic_company = "YD";
        $logisticResult = json_decode($this->getOrderTracesByJson($num, $logistic_code, $logistic_company));

        // dd($logisticResult);
        return view("admin.orders.logistic", ["logistic"=>$logisticResult]);
    }

    /**
     * Json方式 查询订单物流轨迹
     */
    public function getOrderTracesByJson($num, $logistic_code, $logistic_company){
        $requestData = "{'OrderCode':'$num','ShipperCode':'$logistic_company','LogisticCode':'$logistic_code'}";

        $datas = array(
            'EBusinessID' => Config::get('app.kdn_user_id'),
            'RequestType' => '1002',
            'RequestData' => urlencode($requestData) ,
            'DataType' => '2',
        );
        $datas['DataSign'] = $this->encrypt($requestData, Config::get('app.kdn_api_key'));
        $result = $this->sendPost('http://api.kdniao.cc/Ebusiness/EbusinessOrderHandle.aspx', $datas);

        //根据公司业务处理返回的信息......

        return $result;
    }

    /**
     *  post提交数据
     * @param  string $url 请求Url
     * @param  array $datas 提交的数据
     * @return url响应返回的html
     */
    public function sendPost($url, $datas) {
        $temps = array();
        foreach ($datas as $key => $value) {
            $temps[] = sprintf('%s=%s', $key, $value);
        }
        $post_data = implode('&', $temps);
        $url_info = parse_url($url);
        if(empty($url_info['port']))
        {
            $url_info['port']=80;
        }
        $httpheader = "POST " . $url_info['path'] . " HTTP/1.0\r\n";
        $httpheader.= "Host:" . $url_info['host'] . "\r\n";
        $httpheader.= "Content-Type:application/x-www-form-urlencoded\r\n";
        $httpheader.= "Content-Length:" . strlen($post_data) . "\r\n";
        $httpheader.= "Connection:close\r\n\r\n";
        $httpheader.= $post_data;
        $fd = fsockopen($url_info['host'], $url_info['port']);
        fwrite($fd, $httpheader);
        $gets = "";
        $headerFlag = true;
        while (!feof($fd)) {
            if (($header = @fgets($fd)) && ($header == "\r\n" || $header == "\n")) {
                break;
            }
        }
        while (!feof($fd)) {
            $gets.= fread($fd, 128);
        }
        fclose($fd);

        return $gets;
    }

    /**
     * 电商Sign签名生成
     * @param data 内容
     * @param appkey Appkey
     * @return DataSign签名
     */
    public function encrypt($data, $appkey) {
        return urlencode(base64_encode(md5($data.$appkey)));
    }
}
